package vn.edu.saigontech.ncms.web.ajaxtags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.ajaxtags.servlets.BaseAjaxServlet;
import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;

import org.hibernate.Session;
import org.hibernate.Transaction;

import vn.edu.saigontech.ncms.model.bookstore.Item;
import vn.edu.saigontech.ncms.model.program.Level;
import vn.edu.saigontech.ncms.service.ItemService;
import vn.edu.saigontech.ncms.service.LevelService;
import vn.edu.saigontech.ncms.util.Checker;
import vn.edu.saigontech.ncms.util.HibernateUtil;

@SuppressWarnings("serial")
public class LevelItemSearchServlet extends BaseAjaxServlet {
	@Override
	public String getXmlContent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String levelId = request.getParameter("levelId");
		AjaxXmlBuilder xml = new AjaxXmlBuilder();
		Session session = null;
		Transaction trans = null;
		List<Item> items = new ArrayList<Item>();
		try {
			session = HibernateUtil.getCurrentSession();
			trans = session.beginTransaction();
			Level level = LevelService.INSTANCE.findById(Long.parseLong(levelId));
			if (Checker.isNotNull(level)) {
				items = ItemService.INSTANCE.findByLevel(level);
			}
			trans.commit();
		} catch (Exception ex) {
			if (trans != null) {
				trans.rollback();
			}
		} finally {
			if (session != null) {
				session.close();
			}
		}
		xml.addItem("", true, "");
		for (Item item : items) {
			xml.addItem(item.getDisplayName(), true, item.getId().toString());
		}
		return xml.toString();
	}
}
